package com.gitee.androidgoodies.batterylog;

import android.app.LocalActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Environment;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    public final static String ACTION_SHOW_RECORDDATA = "com.gitee.androidgoodies.batterylog.MainActivity.ACTION_SHOW_RECORDDATA";
    public final static String ACTION_UPDATEMENU = "com.gitee.androidgoodies.batterylog.MainActivity.ACTION_UPDATEMENU";
    private static Context mContext;
    private static String mszmRecordDataSavePath;
    private RecordItem mLastShowRecordItem;
    private Menu mMenu;
    private IntentFilter mIntentFilter;
    private TableLayout mTableLayout;
    private int mnTextFontSize;
    private int mnTextBackgroundColor;
    private int mnTextColor;
    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
    protected LocalActivityManager mLocalActivityManager;
    private static final int DEFAULT_THEME = 0;
    private static final int NIGHT_THEME = 1;
    private int mnAppLocale = 0;
    private static final int DEFAULT_LOCALE = 0;
    private static final int ENGLISH_LOCALE = 1;
    private static final int CHINESE_LOCALE = 2;
    private static final int TRADITIONALCHINESE_LOCALE = 3;
    private String BUNDLE_KEY_IS_RELOAD = "BUNDLE_KEY_IS_RELOAD";
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtils.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        mContext = this;
       
        // 设置存储数据的文件目录
        mszmRecordDataSavePath = getApplicationContext().getExternalFilesDir("data") + "/RecordData.dat";  
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ACTION_SHOW_RECORDDATA);
        mIntentFilter.addAction(ACTION_UPDATEMENU);
        registerReceiver(mReceiver, mIntentFilter);

        // 加载主题
        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        int nAppTheme = sp.getInt("nAppTheme", 0);
        switch (nAppTheme) {
            case DEFAULT_THEME:
                setTheme(R.style.AppTheme);
                break;
            case NIGHT_THEME:
                setTheme(R.style.AppTheme_Night);
                break;
            default:
                setTheme(R.style.AppTheme);
                break;
        }

        // 加载用户设置的语言配置
        Resources resources = getResources();// 获得res资源对象
        Configuration config = resources.getConfiguration();// 获得设置对象
        DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
        mnAppLocale = sp.getInt("nAppLocale", 0);
        switch (mnAppLocale) {
            case DEFAULT_LOCALE:
                config.locale = Locale.getDefault();
                break;
            case ENGLISH_LOCALE:
                config.locale = Locale.ENGLISH;
                break;
            case CHINESE_LOCALE:
                config.locale = Locale.SIMPLIFIED_CHINESE;
                break;
            case TRADITIONALCHINESE_LOCALE:
                config.locale = Locale.TRADITIONAL_CHINESE;
                break;
        }
        resources.updateConfiguration(config, dm);
       
        // 载入布局
        setContentView(R.layout.activity_main);
        
        // 隐藏调试功能界面
        if(!BuildConfig.DEBUG){
            LinearLayout debugLinearLayout = (LinearLayout)findViewById(R.id.activitymainLinearLayout1);
            debugLinearLayout.setVisibility(View.GONE);
        }
        
        // 初始化窗口成员
        mTableLayout = findViewById(R.id.activitymainTableLayout1);

        //设置列表字体风格
        TypedValue typedValue0 = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorTextViewBackgroundColor, typedValue0, true);
        mnTextBackgroundColor = typedValue0.data;
        TypedValue typedValue1 = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorTextViewTextColor, typedValue1, true);
        mnTextColor = typedValue1.data;

        //设置底部导航栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            TypedValue typedValue = new TypedValue();
            getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
            getWindow().setNavigationBarColor(typedValue.data);
        }

        // 添加顶部工具栏其他菜单
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClickListener);

        // 设置不同语言的排版
        double nFontSize = (15 * dm.xdpi) / 403.411;
        String szLANTAG = config.locale.toLanguageTag();
        switch (szLANTAG) {
            case "en":
            case "en-CN":
            case "en-US":
                {
                    double dFontSize = nFontSize;
                    dFontSize = dFontSize * 0.95;
                    nFontSize = (int)dFontSize;
                    mnTextFontSize = (int)nFontSize;
                    break;
                }
            case "zh-CN":
            case "zh-Hans-CN":
            case "zh-TW":
            case "zh-Hant-CN":
                {
                    mnTextFontSize = (int)nFontSize;
                    break;
                }
            default:
                String szError = "未处理的语言的排版 : " + szLANTAG + "\n";
                File f = new File(getDiskCacheDir(getApplicationContext()) + File.separator + "MainActivity_ErrorLanguageTag.log");
                try {
                    FileWriter fileWriter =new FileWriter(f, true);
                    fileWriter.append(szError);
                    fileWriter.flush();
                    fileWriter.close();
                } catch (IOException e) {}
                mnTextFontSize = 16;
                break;
        }

        // 判断是否因为更换主题而导致的重启
        /*boolean isReload = false;
         if (savedInstanceState != null) {
         isReload = savedInstanceState.getBoolean(BUNDLE_KEY_IS_RELOAD, false);
         } else {
         isReload = getIntent().getBooleanExtra(BUNDLE_KEY_IS_RELOAD, false);
         }*/
        // 初始化服务启动参数
        /*Intent intentForStartService = new Intent(getApplicationContext(), RecordService.class);
         if (isReload)
         {
         if (savedInstanceState != null)
         {
         Bundle bundle2 = new Bundle();
         bundle2.putSerializable("LastShowRecordItem", savedInstanceState.getSerializable("mLastShowRecordItem"));
         intentForStartService.putExtras(bundle2);
         }
         }*/

        // 开启电量监控服务
        Intent intentForStartService = new Intent(getApplicationContext(), RecordService.class);
        startService(intentForStartService);
        showRecordData();
    }

    @Override
    protected void onDestroy() {
        LogUtils.d(TAG, "onDestroy");
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }   
        //SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        //boolean isKeepService = sp.getBoolean("isKeepService", false);
        //if (!isKeepService)
        //    stopService(new Intent(getApplicationContext(), RecordService.class)); 
        super.onDestroy();
    }
    static int mnTest = 0;
    public void onAddTestRecord(View v){
        Intent intent = new Intent(RecordServiceReceiver.ACTION_ADD_RECORDITEM);
        intent.putExtra(RecordServiceReceiver.EXTRA_INT_BATTERY_PERCENTAGE, mnTest++);
        intent.setComponent(new ComponentName(getPackageName(),getPackageName()+".RecordServiceReceiver"));
        sendBroadcast(intent);
    }
    
    private void showRecordData()
    {
        // 清空列表
        for (int i = mTableLayout.getChildCount() - 1; i > 0; i--) {
            mTableLayout.removeViewAt(i);
        }
        // 读取文件数据
        ArrayList<RecordItem> recordData = new ArrayList<RecordItem>();
        String szmRecordDataSavePath = mszmRecordDataSavePath;
        // 读取旧数据
        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(szmRecordDataSavePath));
            try {
                recordData = (ArrayList<RecordItem>) inputStream.readObject();
            } catch (IOException e) {
                recordData = new ArrayList<RecordItem>();
            } catch (ClassNotFoundException e) {
                recordData = new ArrayList<RecordItem>();
            }
            inputStream.close();
        } catch (IOException e) {
            LogUtils.d(TAG, "IOException: " + mszmRecordDataSavePath + "|" + e.getMessage());                               
        }                       

        if (recordData.size() > 0) {            
            //显示首数据
            RecordItem itemOld = new RecordItem(0, 0);
            RecordItem itemNow = recordData.get(0);
            showRecordItem(itemNow, itemOld);
            //显示剩余数据
            for (int i = 1; i < recordData.size(); i++) {
                itemOld = recordData.get(i - 1);
                itemNow = recordData.get(i);
                showRecordItem(itemNow, itemOld);
            }
        }
    }

    // 显示单项数据
    //
    public void showRecordItem(RecordItem itemNow, RecordItem itemOld) {
        TableRow row = new TableRow(getApplicationContext());
        TextView text0= new TextView(getApplicationContext());
        TextView text1 = new TextView(getApplicationContext());
        TextView text2 = new TextView(getApplicationContext());
        text0.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mnTextFontSize);
        text1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mnTextFontSize);
        text2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mnTextFontSize);

        text0.setBackgroundColor(mnTextBackgroundColor);
        text1.setBackgroundColor(mnTextBackgroundColor);
        text2.setBackgroundColor(mnTextBackgroundColor);

        text0.setTextColor(mnTextColor);

        text1.setTextColor(mnTextColor);
        text2.setTextColor(mnTextColor);

        if (itemOld.mnBatteryPercentage == 0) {
            // 显示第一条消息
            text0.setText("{" + mSimpleDateFormat.format(itemNow.mnRecordTime) + "}");
            row.addView(text0);
            text1.setText("[??%->" + String.valueOf(itemNow.mnBatteryPercentage) + "%]");
            row.addView(text1);
            if (BatteryLogConfigUtils.getConfigIsKeepRecordService(MainActivity.this)) {
                text2.setText(getString(R.string.activity_main_msg_start));
            }else{
                text2.setText(getString(R.string.activity_main_msg_stop));
            }
            row.addView(text2);
            mTableLayout.addView(row);
        } else {
            text0.setText("{" + mSimpleDateFormat.format(itemNow.mnRecordTime) + "}");
            row.addView(text0);
            text1.setText("[" + String.valueOf(itemOld.mnBatteryPercentage) + "%->"
                          + String.valueOf(itemNow.mnBatteryPercentage) + "%]");
            row.addView(text1);
            text2.setText("(" + TimeDifference(itemOld.mnRecordTime, itemNow.mnRecordTime) + ")");
            row.addView(text2);
            mTableLayout.addView(row);  
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(BUNDLE_KEY_IS_RELOAD, true);
        outState.putSerializable("mLastShowRecordItem", mLastShowRecordItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        mMenu = menu;
        // 取得菜单实例
        getMenuInflater().inflate(R.menu.menu_toolbar_base, menu);

        // 语言菜单项打勾
        //

        // 系统语言视图菜单项
        MenuItem  defaultlanguageViewMenuItem = menu.findItem(R.id.action_defaultlanguageview);
        // 英语视图菜单项
        MenuItem  englishViewMenuItem  = menu.findItem(R.id.action_englishview);
        // 简体中文视图菜单项
        MenuItem  chineseViewMenuItem = menu.findItem(R.id.action_chineseview);
        // 繁体中文视图菜单项
        MenuItem  traditionalChineseViewMenuItem  = menu.findItem(R.id.action_traditionalchineseview);
        // 默认主题菜单项
        MenuItem  defaultThemeMenuItem = menu.findItem(R.id.action_defaulttheme);
        // 深夜主题菜单项
        MenuItem  nightThemeMenuItem = menu.findItem(R.id.action_nighttheme);
        // 保持服务菜单项
        MenuItem  keepServiceMenuItem = menu.findItem(R.id.action_keepservice);
        if (mnAppLocale == DEFAULT_LOCALE) {
            defaultlanguageViewMenuItem.setChecked(true);
        } else {
            Resources resources = getResources();// 获得res资源对象
            Configuration config = resources.getConfiguration();// 获得设置对象
            String szLANTAG = config.locale.toLanguageTag();
            switch (szLANTAG) {
                case "en":
                case "en-CN":
                case "en-US":
                    {
                        englishViewMenuItem.setChecked(true);
                        break;
                    }
                case "zh-CN":
                case "zh-Hans-CN":
                    {
                        chineseViewMenuItem.setChecked(true);
                        break;
                    }
                case "zh-TW":
                case "zh-Hant-CN":
                    {
                        traditionalChineseViewMenuItem.setChecked(true);
                        break;
                    }
                default:
                    {
                        LogUtils.d(TAG, "未添加的语言菜单项 : " + szLANTAG);
                        break;
                    }
            }
        }

        // 主题菜单打勾
        //

        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        int nAppTheme = sp.getInt("nAppTheme", 0);
        switch (nAppTheme) {
            case DEFAULT_THEME:
                {
                    defaultThemeMenuItem.setChecked(true);
                    break;
                }
            case NIGHT_THEME:
                {
                    nightThemeMenuItem.setChecked(true);
                    break;
                }
            default:
                {
                    defaultThemeMenuItem.setChecked(true);
                    break;
                }
        }

        //boolean isKeepService = sp.getBoolean("isKeepService", false);
        boolean isKeepService = BatteryLogConfigUtils.getConfigIsKeepRecordService(MainActivity.this);
        keepServiceMenuItem.setChecked(isKeepService);

        return true;
    }

    private void updateMenu() {
        // 保持服务菜单项
        MenuItem  keepServiceMenuItem = mMenu.findItem(R.id.action_keepservice);
        boolean isKeepService = BatteryLogConfigUtils.getConfigIsKeepRecordService(MainActivity.this);
        keepServiceMenuItem.setChecked(isKeepService);
    }

    // 弹出邮件反馈
    //
    public static void mailContact(Context c) {
        Uri uri = Uri.parse("mailto:" + c.getString(R.string.app_email)); 
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.putExtra(Intent.EXTRA_SUBJECT, c.getString(R.string.mailcontact_feedbacktitle)); // 主题
        intent.putExtra(Intent.EXTRA_TEXT, c.getString(R.string.mailcontact_feedbackcontent)); // 正文
        c.startActivity(Intent.createChooser(intent, c.getString(R.string.mailcontact_selectemailtitle)));
    }

    // 弹出应用信息对话框
    //
    private void showAbout() {
        AlertDialog.Builder customDialog = new AlertDialog.Builder(this, R.style.Dialog);
        customDialog.setIcon(R.mipmap.ic_launcher3);
        //填充设置好的自定义布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_about, null);
        TextView t1 = dialogView.findViewById(R.id.dialogaboutTextViewMailToMe);
        t1.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        t1.getPaint().setAntiAlias(true);//抗锯齿
        t1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mailContact(MainActivity.this);
                }
            });
        customDialog.setTitle(getString(R.string.dialog_about_title));
        customDialog.setView(dialogView);
        customDialog.show();
    }

    public void onKeepServiceClick(MenuItem menuItem) {
        //SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        // 原配置取反值导出
        //boolean isKeepService = !sp.getBoolean("isKeepService", false);
        boolean isKeepService = !BatteryLogConfigUtils.getConfigIsKeepRecordService(MainActivity.this);
        // 保存配置
        //sp.edit().putBoolean("isKeepService", isKeepService).commit();
        BatteryLogConfigUtils.setConfigIsKeepRecordService(MainActivity.this, isKeepService);
        // 设置菜单显示
        menuItem.setChecked(isKeepService);
        // 用配置设置服务运行状态
        setRecordServiceStatusByConfig(MainActivity.this);
    }
    
    public void onLineNum(MenuItem menuItem) {
        Intent intent = new Intent(getApplicationContext(), SettingsLineNumActivity.class);
        startActivity(intent);
    }

    public static void setRecordServiceStatusByConfig(Context context) {
        boolean isKeepService = BatteryLogConfigUtils.getConfigIsKeepRecordService(context);
        if (isKeepService) {
            Intent intentForStartService = new Intent(context.getApplicationContext(), RecordService.class);
            context.startService(intentForStartService);
        } else {
            context.stopService(new Intent(context.getApplicationContext(), RecordService.class)); 

        }
        if(mContext != null)
        {
            ((MainActivity)mContext).showRecordData();
        }
    }

    /**
     * 该方法是用来加载菜单布局的
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //加载菜单文件
        getMenuInflater().inflate(R.menu.menu_toolbar_base, menu);
        return true;
    }

    // 响应菜单点击
    private Toolbar.OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_defaulttheme:
                    {
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().putInt("nAppTheme", DEFAULT_THEME).commit();
                        recreate();
                        break;
                    }
                case R.id.action_nighttheme:
                    {
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().putInt("nAppTheme", NIGHT_THEME).commit();
                        recreate();
                        break;
                    }
                case R.id.action_defaultlanguageview:
                    {
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().putInt("nAppLocale", DEFAULT_LOCALE).commit();
                        recreate();
                        break;
                    }
                case R.id.action_englishview:
                    {
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().putInt("nAppLocale", ENGLISH_LOCALE).commit();
                        recreate();
                        break;
                    }
                case R.id.action_chineseview:
                    {
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().putInt("nAppLocale", CHINESE_LOCALE).commit();
                        recreate();
                        break;
                    }
                case R.id.action_traditionalchineseview:
                    {
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().putInt("nAppLocale", TRADITIONALCHINESE_LOCALE).commit();
                        recreate();
                        break;
                    }
                case R.id.action_about:
                    {
                        showAbout();
                        break;
                    }
                case R.id.action_clear:
                    {
                        if (BatteryLogConfigUtils.getConfigIsKeepRecordService(MainActivity.this)) {
                            // 如果服务有开启就使用服务接口保存数据
                            // 通知服务清理数据
                            //自定义一个action
                            Intent intent = new Intent(RecordServiceReceiver.ACTION_REMOVE_RECORDITEM);
                            intent.setComponent(new ComponentName(getPackageName(),getPackageName()+".RecordServiceReceiver"));
                            sendBroadcast(intent);
                        } else {
                            // 如果服务没开启就直接操作文件保存数据

                            // 读取旧数据
                            ArrayList<RecordItem> recordData = new ArrayList<RecordItem>();
                            try {
                                ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(mszmRecordDataSavePath));
                                recordData = (ArrayList<RecordItem>) inputStream.readObject();
                                inputStream.close();
                            } catch (IOException e) {
                                LogUtils.d(TAG, e.getMessage());
                            } catch (ClassNotFoundException e) {
                                LogUtils.d(TAG, e.getMessage());
                            }

                            RecordItem item = recordData.get(recordData.size() - 1);
                            recordData.clear();
                            item.mnRecordTime = System.currentTimeMillis();
                            recordData.add(item);
                            // 保存记录到文件
                            try {
                                ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(mszmRecordDataSavePath));
                                outputStream.writeObject(recordData);
                                outputStream.close();
                            } catch (IOException e) {
                                LogUtils.d(TAG, e.getMessage());
                            }

                            // 显示数据
                            showRecordData();
                        }
                        break;
                    }
            }
            return true;
        }
    };

    // 显示一条窗口消息,并滑动到底部
    //
    /*private void appendMSG(String szMSG) {
        mtvMSG.append(szMSG + "\n");

        // 主窗口自动滑动到底部
        /*msvMSG.post(new Runnable() {
         @Override
         public void run()
         {
         msvMSG.fullScroll(ScrollView.FOCUS_DOWN);
         }
         });
    }*/

    //onKeyDown设置返回按钮：不退出程序，直接返回桌面
    //原文链接：https://blog.csdn.net/qq_35343446/article/details/80784596
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    };

    //Java计算Date类时间差的函数
    //原文链接：https://blog.csdn.net/u013246459/article/details/79645655
    public String TimeDifference(long start, long end) {

        long between = end - start;
        long day = between / (24 * 60 * 60 * 1000);
        long hour = (between / (60 * 60 * 1000) - day * 24);
        long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        //long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
        //- min * 60 * 1000 - s * 1000);
        String strmin = String.format("%02d", min);
        String strs = String.format("%02d", s);
        //String strms = String.format("%03d",ms);
        //String timeDifference = day + "天" + hour + "小时" + strmin + "分" + strs + "秒" + strms + "毫秒";
        String timeDifference = hour + getString(R.string.activity_main_msg_hour)
            + strmin + getString(R.string.activity_main_msg_minute)
            + strs + getString(R.string.activity_main_msg_second);
        return timeDifference;
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_SHOW_RECORDDATA.equals(action)) {
                showRecordData();
            } else if (ACTION_UPDATEMENU.equals(action)) {
                updateMenu();
            }
        }
    };
    

    public String getDiskCacheDir(Context context) {  
        String cachePath = null;  
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())  
            || !Environment.isExternalStorageRemovable()) {  
            cachePath = context.getExternalCacheDir().getPath();  
        } else {  
            cachePath = context.getCacheDir().getPath();  
        }  
        return cachePath;  
    }
    
}
